package com.kedou.net;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.kedou.app.Config;
import com.kedou.app.R;
import com.kedou.application.Myapplication;
import com.kedou.util.DebugUtil;
import com.kedou.util.Util;

/**
 * 用户登陆的网络请求类
 * 
 * @author zhouchao
 * 
 */
public class PostLogin {

	public PostLogin(String username, String password, String os,
			String deviceId, final SuccessCallback successCallback,
			final FailCallback failCallback, final Context context) {
		new NetConnection(
				Util.getSDBaseUrl() + Config.URL_LOGIN,
				HttpMethod.POST,
				new NetConnection.SuccessCallback() {

					@Override
					public void onSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							switch (obj.getInt(Config.KEY_STATUSCODE)) {
							case Config.RESULT_STATUS_SUCCESS:
								if (successCallback != null) {
									successCallback
											.onSuccess(
													obj.getJSONObject(
															Config.KEY_DATA)
															.getString(
																	Config.KEY_TOKEN),
													obj.getJSONObject(
															Config.KEY_DATA)
															.getString(
																	Config.KEY_USERID),
													obj.getJSONObject(
															Config.KEY_DATA)
															.getString(
																	Config.KEY_USERLEVEL),
													obj.getString(Config.KEY_STATUSMSG));
								}
								break;
							default:
								if (failCallback != null) {
									failCallback.onFail(obj
											.getString(Config.KEY_STATUSMSG));
								}
								break;
							}

						} catch (JSONException e) {
							e.printStackTrace();
							if (failCallback != null) {
								failCallback.onFail(context.getResources()
										.getString(R.string.server_have_wrong));
							}
						}
					}
				}, new NetConnection.FailCallback() {

					@Override
					public void onFail() {
						if (failCallback != null) {
							failCallback.onFail(context.getResources()
									.getString(R.string.server_have_wrong));
						}
					}
				}, Config.KEY_USERNAME, username, Config.KEY_PASSWORD,
				password, Config.KEY_OS, os, Config.KEY_DEVICE, deviceId);
	}

	public static interface SuccessCallback {
		void onSuccess(String token, String userId, String userLevel, String msg);
	}

	public static interface FailCallback {
		void onFail(String msg);
	}
}
